<?php
// 应用公共函数
use think\Cache;
use think\Image;
/*
 * @Author: your name
 * @Date: 2020-06-29 09:28:29
 * @LastEditTime: 2020-09-16 19:21:44
 * @LastEditors: 天羽落星辰
 * @Description: In User Settings Edit
 * @FilePath: \WWW\frx\application\api\common.php
 */


// 查询货币涨幅价格
function moneyprice()
{
  // if (Cache::get('moneyprice')) {
  //     $data = Cache::get('moneyprice');
  // }else{
  $rtps = config('site.rtps');

  $data = db('rtp')->whereIn('bizhong', $rtps)->field('type,price,vol,range')->select();
  //     Cache::set('moneyprice', $data,  200);
  // }
  return $data;
}


// 生成二维码调用使用
function getcode($contract, $bool = false, $tjm = '')
{

  // 参数存入
  $value = $contract;
  // header('Content-Type: image/png');
  vendor("phpqrcode.phpqrcode"); //引入工具包
  // 判断是否有这个文件夹  没有的话就创建一个1
  if (!is_dir("uploads/code/")) {
    // 创建文件加
    mkdir("uploads/code/");
  }
  //海报号
  $matrixPointSize = 2.9; // 二维码点的大小：1到10（图片边长=25像素*点的大小）
  $error_level = 'H'; // 纠错级别：L、M、Q、H
  $margin = 1;    //控制生成二维码的空白区域大小
  //设置二维码图片名称，以及存放的路径
  $filename = 'uploads/code/' . time() . rand(10000, 9999999) . '.png';

  //使用类库生成二维码
  \PHPQRCode\QRcode::png($value, $filename, $error_level, $matrixPointSize, $margin);
  // $image_data = chunk_split(base64_encode(fread(fopen($filename, 'r'), filesize($filename))));
  if ($bool) {
    $font_file = dirname(dirname(dirname(__FILE__))) . '/public/assets/fonts/hei.ttf'; // 文字路径
    $bg = \think\Image::open('assets/img/hb.jpg');
    $ewm = \think\Image::open($filename);
    $ewm_w = $ewm->width();     //二维码宽
    $ewm_h = $ewm->height();    //二维码高
    $bg_w = $bg->width();  //背景宽
    $bg_h = $bg->height(); //背景高
    // if (in_array(1, [1, 2, 3])) {
    $bg->water($filename, array(204, 682));
    $bg->text($tjm, $font_file, 12, '#ffffff', array(390, 749));
    // }
    /*elseif ($num_hb == 2) {
      $bg->water($ewm_url, array($bg_w - $ewm_w - 25, 675));
      $bg->text('邀请码 : ' . $tjm, $font_file, 20, '#444444', array($bg_w * 0.29, $bg_h * 0.82));
  }*/

    $bg->save($filename);
  }
  return $filename;
}



// 已经过去多长时间的方式显示时间
function time_is_older_than($time)
{
  if ($time == 0) return 0;
  $time = date('Y-m-d', $time);
  $d2 = ceil((time() - strtotime($time)) / 60 / 60 / 24); //现在的时间减去过去的时间，ceil()进一函数
  return $d2;
}

if (!function_exists('users_vip')) {
  /**
   * vip升级
   * @param array   ['id','level','price']
   */
  function users_vip($user = null)
  {
    if ($user['order_sum'] >= 200 && $user['order_sum'] < 500) {
      $user->level = 1;
      $user->save();
    } elseif ($user['order_sum'] >= 500 && $user['order_sum'] < 1000) {
      $user->level = 2;
      $user->save();
    } elseif ($user['order_sum'] >= 1000 && $user['order_sum'] < 3000) {
      $user->level = 3;
      $user->save();
    } elseif ($user['order_sum'] >= 3000 && $user['order_sum'] < 5000) {
      $user->level = 4;
      $user->save();
    } elseif ($user['order_sum'] >= 5000) {
      $user->level = 5;
      $user->save();
    } else {
      $user->level = 0;
      $user->save();
    }
  }
}

if (!function_exists('user_order_count')) {
  /**
   * 获取订单进行中的累计 
   * @param array  
   * @param array
   */
  function user_order_count($array, $array2)
  {
    $count = 0;
    // 获取进行中的累计
    foreach ($array as $v) {
      foreach ($array2 as $vv) {
        if ($v['id'] == $vv) {
          $count += $v['order_sum'];
        }
      }
    }

    return $count;
  }
}

if (!function_exists('user_shaxia')) {
  /**
   * 统计我的伞下三层用户和直推用户 
   * @param $array  
   * @param $id  
   */
  function user_shaxia($array)
  {
    foreach ($array as &$v) {
      foreach ($array as $vv) {
        $tpath = explode(',', $vv['tpath']);
        // 伞下三代用户
        if (in_array($v['id'], $tpath)) {
          // 我当前位子
          $key_count = array_search(1, $tpath);
          // 从我的位子开始取出数组
          $arr = array_slice($tpath, $key_count, count($tpath));
          // 判断伞下三代用户
          if (count($arr) <= 3) {
            $v['sanxia'][] = $vv['id'];
          }
        }
        if ($v['id'] == $vv['tid']) {
          $v['direct_push'][] = $vv['id'];
        }
      }
    }
    return $array;
  }
}

if (!function_exists('direct_push_f_level')) {
  /**
   * 获取订单进行中的累计 
   * @param $array  
   * @param $id  
   */
  function direct_push_f_level($array, $array2)
  {
    $f_level_count = 0;
    foreach ($array as &$v) {
      foreach ($array as $vv) {
        if ($v == $v['id']) {
          // $f_level_count
        }
      }
    }
    return $array;
  }
}


//等级升级 向上递归找上级判断 $user:触发方法的用户信息
function up_f_level($user)
{
  $setting = config('site');

  $t_user = db('user')->field('id,tid,f_level,status,order_sum')->where('id', $user['tid'])->find();
  if (!$t_user || $t_user['status'] <> 'normal') {
    return false;
  }

  $uid = $t_user['id'];
  $level = $t_user['f_level'];
  if ($level == 1) { //F2升级伞下出现至少3F1
    $lv_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 1)->count();
    if (($lv_num >= $setting['uplevel_f2']) && ($t_user['order_sum'] >= $setting['uplevel_user_f2'])) {
      $level = 2;
      up_f_level($t_user);
    } else {
      return false;
    }
  } elseif ($level == 2) {
    $lv_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 2)->count();
    $lv3_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 3)->count();

    if (($lv_num >= $setting['uplevel_f3']) && ($t_user['order_sum'] >= $setting['uplevel_user_f3'])) {
      $level = 3;
      up_f_level($t_user);
    } elseif (($lv3_num >= $setting['uplevel_users_f3']) && ($t_user['order_sum'] >= $setting['uplevel_user_f3'])) {
      $level = 3;
      up_f_level($t_user);
    } else {
      return false;
    }
  } elseif ($level == 3) {
    $lv_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 3)->count();
    $lv4_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 4)->count();
    if (($lv_num >= $setting['uplevel_f4']) && ($t_user['order_sum'] >= $setting['uplevel_user_f4'])) {
      $level = 4;
      up_f_level($t_user);
    } elseif (($lv4_num >= $setting['uplevel_users_f4']) && ($t_user['order_sum'] >= $setting['uplevel_user_f4'])) {
      $level = 4;
      up_f_level($t_user);
    } else {
      return false;
    }
  } elseif ($level == 4) {
    $lv_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 4)->count();
    $lv5_num = db('user')->where("FIND_IN_SET({$uid},tpath)")->where('f_level', 5)->count();
    if (($lv_num >= $setting['uplevel_f5']) && ($t_user['order_sum'] >= $setting['uplevel_user_f5'])) {
      $level = 5;
      up_f_level($t_user);
    } elseif (($lv5_num >= $setting['uplevel_users_f5']) && ($t_user['order_sum'] >= $setting['uplevel_user_f5'])) {
      $level = 5;
      up_f_level($t_user);
    } else {
      return false;
    }
  } else {
    return false;
  }
  // 满足升级
  if ($level > $t_user['f_level']) {
    $res = db('user')->where('id', $t_user['id'])->update(['f_level' => $level]);
    if ($res) {
      return true;
    } else {
      return false;
    }
  }
}

// 拿几代 递归
function dai($user, $users_id, $dai, &$s_id = array())
{
  if ($dai > 0 && $users_id) {
    $users_idd = db('user')->where(['status' => 'normal'])->where('level', '>', 0)->whereIn('tid', $users_id)->column('id');
    $s_id = array_merge($s_id, $users_idd);
    dai($user, $users_idd, $dai - 1, $s_id);
  }
  return $s_id;
}



// 每个账号累计最高可获得上限
function qianbao_log_money($id)
{
  $jcj_max = config('site.jcj_max');
  $money = db('qianbao_sysetm_log')->where(['uid' => $id, 'type' => 4, 'zt' => '1'])->sum('money');
  if ($money < $jcj_max) {
    return true;
  }
  return false;
}



//用户A在用户B的什么位置
//返回：shang/xia/pang 上面/下面/旁边
function chickusposition($userinfoA, $userinfoB)
{
  if (in_array($userinfoA['id'], explode(",", $userinfoB['tpath']))) {
    return 'shang';
  } elseif (in_array($userinfoB['id'], explode(",", $userinfoA['tpath']))) {
    return 'xia';
  } else {
    return 'pang';
  }
}


// 功能：通过用户名获取用户信息
function userinfobyuname($uname)
{
  $userdata = db('user')->where(array('username' => $uname))->find();
  if (!$userdata) return false;
  return $userdata;
}

// 币种比例 = USDT价格
// usdt= 1BP
function getercprice($currency)
{
  // $mjo = db('interface_cache')->where('type',$currency)->value('price');
  // $mjo = json_decode($mjo['json'],true);
  return db('rtp')->where('bizhong', $currency)->value('price');
}


//  查询REC20交易记录
function erctransactions($addr, $cointype)
{
  try {
    $cointype = strtoupper($cointype);
    $url = config('cbtapi')['url'];
    $param['apikey'] = config('cbtapi')['apikey'];
    if ($cointype == 'ETH') {
      // 暂时不支持EHT交易记录查询
      // $url = $url . 'getbalance';
      // $param['address'] = $addr;
    } else {
      $url = $url . 'erctransactions';
      $param['address'] = $addr;
      $param['contractaddress'] = config('site.erc_contract')[$cointype];
      $param['offset'] = 50;
    }
    // $ret = \fast\Http::post($url,$param);
    $ret = Http($url, $param);
    $ret = json_decode($ret, true);
    if ($ret['code'] != 1) {
      throw new \Exception($ret['msg'], 1);
    }
  } catch (\Exception $th) {
    trace($th->getMessage(), '查询REC20交易记录 error');
  }

  return $ret['data'];
}


// 领导奖计算
function reward($user, $row, &$sort = 0, &$data_usdt = array(), &$data_tcc = array(), &$users = array())
{

  $data = [];
  $config = config('site');
  $user_tid = userinfobyid($user['tid']);
  if ($user_tid) {
    if ($user_tid['level'] > 0) {
      // dump($row);die;
      $sort = $row['money'] * ($config['ld_f' . $user_tid['level'] . ''] / 100);
      if ($data_usdt) {
        $money = array_sum(array_column($data_usdt, 'money'));
        // 当前收益是否大于你伞下收益
        if ($sort > $money) {
          $sort -= $money;
          if ($user_tid['tcc'] <= $sort) {
            $sort = $user_tid['tcc'];
          }
        } else {
          $sort = 0;
        }
      } else {
        if ($user_tid['tcc'] <= $sort) {
          $sort = $user_tid['tcc'];
        }
      }
      // 是否益大于0
      if ($sort > 0) {
        $qian_tcc_parameter = [
          'uid' => $user_tid['id'],
          'uname' => $user_tid['username'],
          'bizhong' => 'tcc',
          'money' =>  -$sort,
          'before' => $user_tid['tcc'],
          'after' => $user_tid['tcc'] - $sort,
          'type' => 9,
          'zt' => 1,
          'memo' => '消耗TCC',
        ];
        $qian_usdt_parameter = [
          'uid' => $user_tid['id'],
          'uname' => $user_tid['username'],
          'bizhong' => 'usdt',
          'money' =>  $sort,
          'zt' => 1,
          'before' => $user_tid['usdt'],
          'after' => $user_tid['usdt'] + $sort,
          'type' => 8,
          'memo' => '领导有方奖励奖励USDT',
          // 'note' => $row['danhao'],
        ];
        $data_tcc[] = $qian_tcc_parameter;
        $data_usdt[] = $qian_usdt_parameter;
        $user_tid['tcc'] -= $sort;
        $user_tid['usdt'] += $sort;
        $user_t = [
          'id' => $user_tid['id'],
          'tcc' => $user_tid['tcc'],
          'usdt' => $user_tid['usdt']
        ];
        $users[] = $user_t;
      }
      reward($user_tid, $row, $sort, $data_usdt, $data_tcc, $users);
    } else {
      reward($user_tid, $row, $sort, $data_usdt, $data_tcc, $users);
    }
  }

  $qian_log = array_merge($data_usdt, $data_tcc);
  if ($qian_log) {
    $data['users'] =  $users;
    $data['qian_log'] =  $qian_log;
  }
  return $data;
}

function ad($user, $order, &$data_usdt = array(), &$users = array(), &$data_usdt_money = array(), &$users_f_love = array(), &$f_love = array())
{

  $data = [];
  $config = config('site');
  $user_tid = userinfobyid($user['tid']);

  if ($user_tid) {
    if ($user_tid['f_level'] > 0) {

     
      // 判断收益是否领取
      if (!db('qianbao_sysetm_log')->where('uid', $user_tid['id'])->where('type', 3)->where('note', $order['danhao'])->count()) {
        // 收益
        $sort = $order['price'] * $config['uplevel_shouyi_f' . $user_tid['f_level'] . ''] / 100;
        if ($data_usdt_money) {
          $money = array_sum($data_usdt_money);
          // 当前收益是否大于你伞下收益
          if ($sort > $money) {
            $sort -= $money;
          } else {
            $sort = 0;
          }
        }

        // 是否益大于0
        if ($sort > 0) {
          $qian_usdt_parameter = [
            'uid' => $user_tid['id'],
            'uname' => $user_tid['username'],
            'bizhong' => 'usdt',
            'money' =>  $sort,
            'zt' => 1,
            'before' => $user_tid['usdt'],
            'after' => $user_tid['usdt'] + $sort,
            'type' => 3,
            'memo' => '团队奖励USDT',
            'note' => $order['danhao'],
          ];

          $data_usdt[] = $qian_usdt_parameter;
          $data_usdt_money[] = $sort;

          $user_tid['usdt'] += $sort;
          $user_t = [
            'id' => $user_tid['id'],
            'usdt' => $user_tid['usdt']
          ];
          $users[] = $user_t;

          // 保存平级等级已领取，之后做判断
          if (!in_array($user_tid['f_level'], $users_f_love)) {
            $users_f_love[] = $user_tid['f_level'];
          }
          ad($user_tid, $order, $data_usdt, $users, $data_usdt_money, $users_f_love, $f_love);
        } else {
          // 平级奖
          // 是否存在平级等级
          if (in_array($user_tid['f_level'], $users_f_love)) {
            // 平级等级是否被领取
            if (!in_array($user_tid['f_level'], $f_love)) {
              // 目前平级没有各级别的奖励划分。统一一个奖励划分
              // 平级奖
              // if($user_tid['id'] == 1){
              //   dump($users_f_love);die;
              // }
              $moeny_pj = $order['price'] * $config['level_award'] / 100;
              $qian_usdt_parameter = [
                'uid' => $user_tid['id'],
                'uname' => $user_tid['username'],
                'bizhong' => 'usdt',
                'money' =>  $moeny_pj,
                'before' => $user_tid['usdt'],
                'after' => $user_tid['usdt'] + $moeny_pj,
                'type' => 9,
                'zt' => 1,
                'memo' => '平级奖励USDT',
                'note' => $order['danhao'],
              ];
              $data_usdt[] = $qian_usdt_parameter;
              $user_tid['usdt'] += $moeny_pj;
              $user_t = [
                'id' => $user_tid['id'],
                'usdt' => $user_tid['usdt']
              ];
              $users[] = $user_t;
              $f_love[] = $user_tid['f_level'];
              ad($user_tid, $order, $data_usdt, $users, $data_usdt_money, $users_f_love, $f_love);
            }
          }
        }

        // ad($user_tid, $order, $data_usdt, $users, $data_usdt_money, $users_f_love, $f_love);
      } else {
        // 虽然我伞下已经拿了，但是你的等级还未超过我。所以需要极差拿奖励
        // 开始 收益
        $sort = $order['price'] * $config['uplevel_shouyi_f' . $user_tid['f_level'] . ''] / 100;
        if ($data_usdt_money) {
          $money = array_sum($data_usdt_money);

          // 当前收益是否大于你伞下收益
          if ($sort > $money) {
            $sort -= $money;
          } else {
            $sort = 0;
          }
        }
        $data_usdt_money[] = $sort;
        ad($user_tid, $order, $data_usdt, $users, $data_usdt_money, $users_f_love, $f_love);
      }
    } else {
      ad($user_tid, $order, $data_usdt, $users, $data_usdt_money, $users_f_love, $f_love);
    }
  }

  $qian_log = $data_usdt;
  if ($qian_log) {
    $data['users'] =  $users;
    $data['qian_log'] =  $qian_log;
  }
  return $data;
}



function profit_partner($user, $order, &$data_usdt = array(), &$users = array(), &$data_usdt_money = array())
{
  $data = [];
  $config = config('site');

  $user_tid = userinfobyid($user['tid']);

  if ($user_tid) {
    // if($user)
    if (isset($config['partner'][$user_tid['username']]) || isset($config['partner'][strtoupper($user_tid['username'])])) {

      // dump($user['username']);die;
      if (isset($config['partner'][$user_tid['username']])) {
        $partner = $config['partner'][$user_tid['username']];
      } elseif (isset($config['partner'][strtoupper($user_tid['username'])])) {
        $partner = $config['partner'][strtoupper($user_tid['username'])];
      }
      // 判断收益是否领取
      if (!db('qianbao_sysetm_log')->where('uid', $user_tid['id'])->where('type', 11)->where('note', $order['danhao'])->count()) {


        // dump($partner);

        // 收益
        $sort = $order['price'] * $partner / 100;
        if ($data_usdt_money) {
          $money = array_sum($data_usdt_money);
          // 当前收益是否大于你伞下收益
          if ($sort > $money) {
            $sort -= $money;
          } else {
            $sort = 0;
          }
        }

        // 是否益大于0
        if ($sort > 0) {
          $qian_usdt_parameter = [
            'uid' => $user_tid['id'],
            'uname' => $user_tid['username'],
            'bizhong' => 'usdt',
            'money' =>  $sort,
            'zt' => 1,
            'before' => $user_tid['usdt'],
            'after' => $user_tid['usdt'] + $sort,
            'type' => 11,
            'memo' => '合伙人奖励USDT',
            'note' => $order['danhao'],
          ];
          $data_usdt[] = $qian_usdt_parameter;

          $data_usdt_money[] = $sort;

          $user_tid['usdt'] += $sort;
          // dump($user_tid);
          $user_t = [
            'id' => $user_tid['id'],
            'usdt' => $user_tid['usdt']
          ];
          $users[] = $user_t;
          // dump($users);
          profit_partner($user_tid, $order, $data_usdt, $users, $data_usdt_money);
        }
      } else {
        // 虽然我伞下已经拿了，但是你的等级还未超过我。所以需要极差拿奖励
        // 开始 收益

        $sort = $order['price'] * $partner / 100;
        if ($data_usdt_money) {
          $money = array_sum($data_usdt_money);
          // 当前收益是否大于你伞下收益
          if ($sort > $money) {
            if ($sort > $money) {
              $sort -= $money;
            } else {
              $sort = 0;
            }
          }
        }
        $data_usdt_money[] = $sort;
        // 结束收益
        // 是否益大于0
        // if ($sort > 0) {
        profit_partner($user_tid, $order, $data_usdt, $users, $data_usdt_money);
        // }
      }
    } else {
      // dump($users);
      profit_partner($user_tid, $order, $data_usdt, $users, $data_usdt_money);
    }
  }

  $qian_log = $data_usdt;
  if ($qian_log) {
    $data['users'] =  $users;
    $data['qian_log'] =  $qian_log;
  }
  return $data;
}
